/*
 * http.hpp
 *
 *  Created on: Dec 5, 2010
 *      Author: daniel
 */

#ifndef HTTP_HPP_
#define HTTP_HPP_

#include <boost/asio.hpp>
#include <boost/bind.hpp>
#include <boost/function.hpp>
#include <doeplus/webapp/protocol/http_connection.hpp>
#include <doeplus/webapp/server.hpp>
#include <doeplus/webapp/connection.hpp>
#include <set>


namespace doeplus{ namespace webapp{


class http_server : public server {

private:
	boost::asio::ip::tcp::endpoint _endpoint;
	boost::asio::ip::tcp::acceptor _acceptor;

	connection::ptr next_connection;
	//http_connection* next_http_connection;

	/**
	 * Accept a new connection and then start a new one
	 */
	void handle_accept(connection::ptr connection,const boost::system::error_code& error){
		if(!error){
			//this->_active_connections.insert(connection);
			connection.get()->start(this);
			this->start_accept();
		}
	}

	/**
	 * Wait for a new connection
	 */
	void start_accept(){
		protocol::http_connection *http_con_ptr( new protocol::http_connection(this->_io_service,this->default_headers) );
//		http_con_ptr->init(this);
		this->next_connection.reset(http_con_ptr);
		this->_acceptor.async_accept(
				http_con_ptr->socket(),
				boost::bind(&http_server::handle_accept,this,this->next_connection,boost::asio::placeholders::error)
		);
	}

public:
	http_server(boost::asio::io_service &io_service,std::string bind_ip,int port):
		server(io_service),
		_endpoint(boost::asio::ip::tcp::v4(),port),
		_acceptor(io_service,_endpoint)
	{
		this->start_accept();
	}


};


} } // doeplus::webapp

#endif /* HTTP_HPP_ */
